/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import { Form, Input, Checkbox, Select, TreeSelect, Button, message, Upload, Icon, Modal } from 'antd';
import {connect} from 'dva';
import moment from 'moment';

import request from '@/utils/request';
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import ExportMeterData from '../Owner/ExportMeterData';
import styles from './index.less';
const { TreeNode } = TreeSelect;
const FormItem = Form.Item;
const Option = Select.Option;
@connect(({ article_manage, loading,global }) => ({
  article_manage,
  global,
  loading: loading.models.article_manage,
}))
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      all_roles:[],
      all_receiver:[],
      editorState: BraftEditor.createEditorState(''), // 设置编辑器初始内容
      indeterminate: false,
      checkAll: false,
      checkedList:[],
      fileList:[],
      show_cover_image:false,
      src: null,
      hasOriginImg:false,
      crop: {
        unit: '%',
        width: 100,
        aspect: 3 / 2,
      },
    };
  }
  componentDidMount() {
    const that=this;
    if(!this.props.editRecord){
      const mailHistory=localStorage.getItem('mailHistory');
      if(mailHistory){
        this.setState({
          editorState:BraftEditor.createEditorState(mailHistory)
        })
      }
      this.timer=setInterval(function() {
        console.log('保存草稿')
        localStorage.setItem('mailHistory',that.state.editorState.toHTML())
      },10000)
    }else{
      this.setState({
        editorState:BraftEditor.createEditorState(this.props.editRecord.content)
      })
      this.props.form.setFieldsValue({
        type:this.props.editRecord.type,
      })
      if(this.props.editRecord.type.indexOf('1')>=0||
        this.props.editRecord.type.indexOf('7')>=0){
        that.setState({
          show_cover_image:true,
          hasOriginImg:true,
        })
      }else{
        that.setState({
          show_cover_image:false
        })
      }
    }


  }
  componentWillUnmount() {
    if(this.timer){
      clearInterval(this.timer)
    }
  }

  handleChange = (editorState) => {
    this.setState({
      editorState: editorState,
      // outputHTML: editorState.toHTML()
    })
  }

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 2},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 22},
      }
    };

    const {getFieldDecorator} = this.props.form;
    const { dispatch } = this.props;
    const myUploadFn = (param) => {
      const fd = new FormData()
      fd.append('file', param.file)

      request(`/images`, {
        method: 'POST',
        data:fd
      }).then((response)=> {
        console.log('images response', response)
        if(response.status===200){
          param.success({
            url: response.data.data.path,
            meta: {
              id: 'xxx',
              title: '照片',
              alt: '照片',
              loop: true, // 指定音视频是否循环播放
              autoPlay: true, // 指定音视频是否自动播放
              controls: true, // 指定音视频是否显示控制栏
              poster: 'http://xxx/xx.png', // 指定视频播放器的封面
            }
          })
        }
      })
    }
    const that=this;
    const props = {
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [file],
        }));
        return false;
      },
      fileList: this.state.fileList,
      accept:".png, .jpg, .jpeg"
    };
    return (
      <div>
        <Form onSubmit={this.handleSubmit} style={{paddingBottom:'50px'}}>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              文章标题
            </span>
            )}>
            {getFieldDecorator('title', {
              initialValue:this.props.editRecord?this.props.editRecord.title:'',
              rules: [{required: true, message:'标题不能为空'}],
            })(
             <Input/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            help={'首页轮播和党员风采必须选择封面图片'}
            label={(
              <span>
              文章板块
            </span>
            )}>
            {getFieldDecorator('type', {
              initialValue:[],
              rules: [{required: true, message:'类型不能为空'}],
            })(
              <Select onChange={(value)=>{
                if(value.indexOf('1')>=0||value.indexOf('7')>=0){
                  that.setState({
                    show_cover_image:true
                  })
                }else{
                  that.setState({
                    show_cover_image:false,
                    fileList:[],
                  })
                }
              }}  mode="multiple" allowClear={false}>
                {
                  [{id:'1',name:'首页轮播'},{id:'2',name:'党建动态'},{id:'3',name:'时事要闻'},{id:'4',name:'活动会议'},{id:'5',name:'主题党日'},
                    {id:'6',name:'支部荣誉'},{id:'7',name:'党员风采'},{id:'8',name:'学习内容'}].map((item,index)=>{
                    return  <Option key={index}   value={item.id}>
                      {item.name}</Option>
                  })
                }
              </Select>

            )}
          </FormItem>
          {
            this.state.show_cover_image&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
              封面图片
            </span>
              )}
              help={'推荐使用长宽比为3:2图片'}> {getFieldDecorator('image', {
              rules: [{required: true}],
            })(
                <div className="dropbox">
                  {getFieldDecorator('file', {
                    rules: [{required: true, message:''}],
                  })(
                    <Upload {...props} style={{width:'100%'}}>
                      {
                        (this.props.editRecord&&this.props.editRecord.cover_image_path)?
                          this.state.fileList.length>0?<Button icon={'upload'} className={'btn-green'} block={true}>
                              点击选择
                            </Button>:
                          <img src={this.props.editRecord.cover_image_path} style={{width:'100px'}} alt=""/>:
                          <Button icon={'upload'} className={'btn-green'} block={true}>
                            点击选择
                          </Button>
                      }
                    </Upload>
                  )}
                </div>
            )}
            </FormItem>
          }

         {/* <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              文章标签
            </span>
            )}>
            {getFieldDecorator('tag', {
              initialValue:this.props.editRecord?this.props.editRecord.tag:'',
            })(
              <Input/>
            )}
          </FormItem>*/}
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              文章内容
            </span>
            )}>
            {getFieldDecorator('content', {
              rules: [{required: true, message:'内容不能为空'}],
            })(
              <div className="editor-wrapper">
                <BraftEditor
                  excludeControls={['link']}
                  value={this.state.editorState}
                  onChange={this.handleChange}
                  media={{uploadFn: myUploadFn}}
                  accepts={{
                    image: 'image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg',
                    video: false,
                    audio: false
                  }}
                />
              </div>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              转载来源
            </span>
            )}>
            {getFieldDecorator('reprinted_source', {
              initialValue:this.props.editRecord?this.props.editRecord.reprinted_source:'',
            })(
              <Input/>
            )}
          </FormItem>
        </Form>
        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={()=>{
            localStorage.setItem('mailHistory',this.state.editorState.toHTML())
            this.props.onClose()
          }} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={()=>{
            let formData = new FormData();
            console.log(this.props.form.getFieldsValue())
            console.log(this.state.croppedImageUrl)
            if(!this.props.form.getFieldsValue().title){
              message.error('标题不能为空')
              return false
            }
            if(!this.props.form.getFieldsValue().type){
              message.error('类型不能为空')
              return false

            }
            if(!this.state.editorState.toHTML()){
              message.error('内容不能为空')
              return false
            }
            const that = this;
            if(this.props.editRecord&&this.props.form.getFieldsValue().hasOwnProperty('image')){
              //cover_image_path

              if(this.state.fileList.length>0){
                this.state.fileList.forEach(file => {
                  formData.append('cover_image', file);
                })
              }else if(this.props.editRecord.cover_image_path){

              }else{
                message.error('封面图片不能为空')
                return false
              }
            }else {
              formData.append('cover_image_delete', 1);
            }
            if(!this.props.editRecord){
              if(this.state.show_cover_image&&this.state.fileList.length===0){
                message.error('封面图片不能为空')
                return false
              }else{
                this.state.fileList.forEach(file => {
                  formData.append('cover_image', file);
                })
              }
            }


            this.props.form.getFieldsValue().type.forEach(item => {
              formData.append('type[]', item);
            })
            formData.append("title", this.props.form.getFieldsValue().title);
            formData.append("reprinted_source", this.props.form.getFieldsValue().reprinted_source);
            formData.append("date", moment().format('YYYY-MM-DD'));
            formData.append("content", this.state.editorState.toHTML());
            dispatch({
              type: this.props.editRecord?'article_manage/edit':'article_manage/add',
              payload:this.props.editRecord?{
                id:this.props.editRecord.id,
                formData:formData
              }:formData,
              callback() {
                message.success(that.props.editRecord?'编辑文章成功':'添加文章成功');
                const {
                  article_manage: { searchParams },
                } = that.props;
                that.props.handleSearch(searchParams);
                that.props.onClose();
              },
            });
          }} type="primary">
            发布
          </Button>
        </div>
        <Modal
          title={`编辑图片`}
          visible={this.state.imgModal}
          centered
          onOk={() => {
            this.setState({ imgModal: false, editRecord: {} });
          }}
          className="imgModal"
          onCancel={() => {
            this.setState({ imgModal: false, editRecord: {} });
          }}

        >
          {this.state.src && (
            <ReactCrop
              src={this.state.src}
              crop={this.state.crop}
              ruleOfThirds
              onImageLoaded={this.onImageLoaded}
              onComplete={this.onCropComplete}
              onChange={this.onCropChange}
            />
          )}

        </Modal>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default (AddPoliciesFormWrap);
